package com.redoor.app.stake.basicdata.mq.consumerService;

import com.alibaba.fastjson.JSON;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.redoor.app.stake.basicdata.model.BaseMqOperationLog;
import com.redoor.app.stake.basicdata.model.LogEnum;
import com.redoor.app.stake.basicdata.model.SyncOrganization;
import com.redoor.app.stake.basicdata.service.LogService;
import com.redoor.app.stake.basicdata.service.SyncOrganizationService;
import com.redoor.app.stake.common.utils.UUIDTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import sunbox.core.hsf.api.SysManageService;
import sunbox.core.hsf.vo.OrganizationItem;
import sunbox.core.vo.api.OpenAPIResponse;


/**
 * 科东修改组织机构后，会将向外发送MQ消息，topic为 qfjs_sys_org 消息体为ouCode
 *
 * Created by xull on 2017/11/23.
 */
@Service
public class UpdateOrganizationMessageListener implements MessageListener {

    private static final Logger logger = LoggerFactory.getLogger(UpdateOrganizationMessageListener.class) ;


    @Autowired
    SysManageService sysManageService;

    @Autowired
    private SyncOrganizationService syncOrganizationService;

    @Autowired
    LogService logService;

    /**
     * 监听处理程序
     *
     * @param message
     * @param context
     * @return
     */
    @Override
    public Action consume(Message message, ConsumeContext context) {
        String ouCode = new String(message.getBody()) ;   // 科东传递过来的参数是一个String，不是Json，所以需要转换
        String tag = message.getTag() ;
        logger.info("UpdateOrgMessageListener get mq body = " + ouCode) ;
        if(StringUtils.isEmpty(ouCode)){
            logger.info("topic UpdateOrgMessageListener get mq tag=" + tag) ;
        } else {
            /*mq日志记录*/
            BaseMqOperationLog baseMqOperationLog = new BaseMqOperationLog();
            baseMqOperationLog.setUuid(UUIDTool.getUUID());
            baseMqOperationLog.setMessagetopic(message.getTopic());
            baseMqOperationLog.setMessagebody(message.getBody().toString());
            baseMqOperationLog.setMessagetag(tag);
            baseMqOperationLog.setType(2);

            this.updateOrg(tag,ouCode,baseMqOperationLog) ;
        }
        return Action.CommitMessage ;
    }

    /**
     * 组织机构编码修改处理
     * @param ouCode
     */
    private void updateOrg(String tag,String ouCode,BaseMqOperationLog baseMqOperationLog){
        try{
            logger.info("UpdateOrgMessageListener == > dbSession："+syncOrganizationService+"  tag:"+tag+"  ouCode:"+ouCode);
            if(tag==null && tag.trim().length()==0){
                logger.info("UpdateOrgMessageListener-->updateOrg-->科东发送的tag为空!");
                return ;
            }

            //根据ouCode获取资产的组织机构信息
            SyncOrganization syncOrganization = null;
            if(tag.equals("create") || tag.equals("update")){
                //根据ouCode获取科东的组织机构信息
                logger.info("修改组织机构开始");
                //调取科东接口根据MQ发送ouCode查询对应组织机构信息
                OpenAPIResponse resp = this.sysManageService.getSingleOrgByOuCode("",ouCode);
                logger.info("科东返回的机构信息:"+JSON.toJSONString(resp));
                OrganizationItem organizationItem = (OrganizationItem)resp.getData() ;

                syncOrganization = new SyncOrganization();
                syncOrganization.setOrgno(organizationItem.getOuCode());
                syncOrganization.setName(organizationItem.getOuName());
                syncOrganization.setStandardcode(organizationItem.getStandardCode());
                syncOrganization.setUuid(UUIDTool.getUUID());
                syncOrganization.setParentorgno(organizationItem.getParentOuCode());
                //从接口中获取级别,与现有项目兼容不清楚 TODO
                syncOrganization.setLevel(organizationItem.getOuLevel());
                syncOrganization.setCreatedat(organizationItem.getCreateTime());
                syncOrganization.setCreatoruuid(organizationItem.getCreator());
                if(organizationItem==null){
                    logger.info("根据ouCode"+ouCode+"查询到的机构实体为空!");
                    return ;
                }
                //根据唯一索引orgNo进行判断有则修改,无则新增
                if(0 < this.syncOrganizationService.inserOrUpdateByOrgNoToSyncOrganization(syncOrganization)){
                    logService.addLogToRedis(baseMqOperationLog, LogEnum.MQ_LOG);
                }
                logger.info("修改组织机构完成");
            }else if(tag.equals("delete")){
                // 删除组织机构，假删除，将status设置为1001
                if(0 < this.syncOrganizationService.deleteByOrgNo(ouCode)){
                    logService.addLogToRedis(baseMqOperationLog, LogEnum.MQ_LOG);
                }
            }

        } catch(Exception e){
            logger.info("ywjx update stake status throws exception ") ;
            e.printStackTrace() ;
        }
    }

}